﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace RecordBill.Core
{
    public class FileDownloader
    {
        public static async Task<bool> DownloadExcelFileAsync(string fileUrl, string savePath)
        {
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    // 设置超时时间（可选）
                    httpClient.Timeout = TimeSpan.FromMinutes(5);

                    // 发送GET请求获取文件流
                    using (HttpResponseMessage response = await httpClient.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead))
                    {
                        // 确保响应成功
                        response.EnsureSuccessStatusCode();

                        // 读取响应内容流
                        using (Stream contentStream = await response.Content.ReadAsStreamAsync(),
                                      fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                        {
                            // 将流写入文件
                            await contentStream.CopyToAsync(fileStream);
                        }
                    }
                }

                Console.WriteLine("文件下载完成，保存路径: " + savePath);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"下载文件时出错: {ex.Message}");
                return false;
            }
        }
    }
}
